<template>
  <div class="app-container dashboard">
    <!-- 顶部统计信息卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="number-container">
              <span class="number">{{ statistics.projects || 0 }}</span>
            </div>
            <div class="label">项目总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="number-container">
              <span class="number">{{ statistics.online || 0 }}</span>
            </div>
            <div class="label">在线数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="number-container">
              <span class="number">{{ statistics.offline || 0 }}</span>
            </div>
            <div class="label">离线数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="number-container">
              <span class="number">{{ statistics.alarms || 0 }}</span>
            </div>
            <div class="label">报警数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="number-container">
              <span class="number">{{ statistics.users || 1 }}</span>
            </div>
            <div class="label">用户数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="control-panel">
              <el-select v-model="mapTheme" placeholder="选择主题" size="small" @change="changeMapTheme">
                <el-option label="深蓝" value="midnight"></el-option>
                <el-option label="标准" value="normal"></el-option>
                <el-option label="卫星" value="earth"></el-option>
              </el-select>
              <el-button size="small" icon="Refresh" @click="refreshMap"></el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 地图容器 -->
    <div class="map-container">
      <div id="mapContainer" ref="mapContainerRef"></div>
      <div class="map-controls">
        <div class="map-button" @click="toggleFlylines">{{ showFlylines ? '隐藏飞线' : '显示飞线' }}</div>
        <div class="map-button" @click="toggle3DBar">{{ show3DBar ? '隐藏柱状图' : '显示柱状图' }}</div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import { onMounted, ref, onUnmounted, reactive, watch } from 'vue';
import * as echarts from 'echarts';
import 'echarts-gl';

// 百度地图API全局对象
let BMapGL = null;

// 响应式数据
const mapContainerRef = ref(null);
const mapTheme = ref('normal');
const showFlylines = ref(false);
const show3DBar = ref(false);
const statistics = reactive({
  projects: 0,
  online: 0,
  offline: 0,
  alarms: 0,
  users: 1
});

// 地图相关实例
let map = null;
let chart = null;
const markers = [];
const infoWindows = [];
const flylineOverlays = [];

// 模拟点位数据 (注意：百度地图坐标系不同于高德，需要转换)
const mockLocationData = [
  { name: '广州市立创精细化工有限公司', value: [113.270793, 23.135308], type: 'online', count: 85 },
  { name: '深圳总部', value: [114.057868, 22.543099], type: 'online', count: 120 },
  { name: '上海分公司', value: [121.473701, 31.230416], type: 'offline', count: 65 },
  { name: '北京分公司', value: [116.413554, 39.910816], type: 'offline', count: 78 },
  { name: '武汉工厂', value: [114.305469, 30.593175], type: 'alarm', count: 36 },
  { name: '成都分公司', value: [104.066143, 30.572269], type: 'online', count: 92 },
  { name: '西安办事处', value: [108.946465, 34.347269], type: 'online', count: 45 },
  { name: '杭州研发中心', value: [120.21201, 30.2084], type: 'online', count: 110 }
];

// 模拟飞线数据
const mockFlylineData = [
  { fromName: '广州市立创精细化工有限公司', toName: '深圳总部', coords: [[113.270793, 23.135308], [114.057868, 22.543099]], count: 30 },
  { fromName: '广州市立创精细化工有限公司', toName: '上海分公司', coords: [[113.270793, 23.135308], [121.473701, 31.230416]], count: 20 },
  { fromName: '广州市立创精细化工有限公司', toName: '北京分公司', coords: [[113.270793, 23.135308], [116.413554, 39.910816]], count: 25 },
  { fromName: '深圳总部', toName: '成都分公司', coords: [[114.057868, 22.543099], [104.066143, 30.572269]], count: 15 },
  { fromName: '深圳总部', toName: '西安办事处', coords: [[114.057868, 22.543099], [108.946465, 34.347269]], count: 12 },
  { fromName: '深圳总部', toName: '杭州研发中心', coords: [[114.057868, 22.543099], [120.21201, 30.2084]], count: 22 }
];

// 加载百度地图脚本
function loadBMapScript() {
  return new Promise((resolve, reject) => {
    // 检查是否已加载
    if (window.BMapGL) {
      BMapGL = window.BMapGL;
      resolve(BMapGL);
      return;
    }
    
    // 创建script标签
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=KW4uNC7LmFI57LyWjLvvB6F27xxyGq1c&callback=initBMapGL`;
    
    // 定义回调函数
    window.initBMapGL = function() {
      BMapGL = window.BMapGL;
      resolve(BMapGL);
    };
    
    // 处理加载错误
    script.onerror = function() {
      reject(new Error('百度地图脚本加载失败'));
    };
    
    // 添加到文档
    document.head.appendChild(script);
  });
}

// 初始化百度地图
async function initBMap() {
  try {
    // 加载百度地图API
    await loadBMapScript();
    
    // 创建地图实例
    map = new BMapGL.Map('mapContainer', {
      enableMapClick: false
    });
    
    // 设置中心点和缩放级别
    const centerPoint = new BMapGL.Point(116.404, 39.915);
    map.centerAndZoom(centerPoint, 5);
    
    // 启用地图操作功能
    map.enableScrollWheelZoom();
    map.enableDragging();
    map.enableDoubleClickZoom();
    map.enableKeyboard();
    
    // 设置地图主题
    setMapTheme(mapTheme.value);
    
    // 添加标记点
    addMapMarkers();
    
    // 更新统计数据
    updateStatistics();
    
  } catch (error) {
    console.error('百度地图加载失败', error);
    initEChartsMap(); // 如果百度地图加载失败，使用ECharts作为替代
  }
}

// 添加地图标记点
function addMapMarkers() {
  if (!map || !BMapGL) return;
  
  // 清除已有标记
  clearOverlays();
  
  // 创建点标记
  mockLocationData.forEach(item => {
    // 根据类型设置不同颜色
    let color = '#67C23A'; // 在线-绿色
    if (item.type === 'offline') {
      color = '#909399'; // 离线-灰色
    } else if (item.type === 'alarm') {
      color = '#F56C6C'; // 报警-红色
    }
    
    // 创建坐标点
    const point = new BMapGL.Point(item.value[0], item.value[1]);
    
    // 创建自定义图标
    const iconUrl = `data:image/svg+xml;base64,${btoa(`
      <svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
        <circle cx="16" cy="16" r="12" fill="${color}" stroke="white" stroke-width="2"/>
      </svg>
    `)}`;
    
    const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(16, 16), {
      imageSize: new BMapGL.Size(16, 16)
    });
    
    // 创建标记
    const marker = new BMapGL.Marker(point, { icon });
    marker.setTitle(item.name);
    map.addOverlay(marker);
    markers.push(marker);
    
    // 创建信息窗口
    const infoWindow = new BMapGL.InfoWindow(`<div style="padding: 8px;">${item.name}</div>`, {
      width: 200,
      height: 60,
      title: ""
    });
    infoWindows.push(infoWindow);
    
    // 添加点击事件
    marker.addEventListener('click', function() {
      map.openInfoWindow(infoWindow, point);
    });
  });
}

// 清除所有覆盖物
function clearOverlays() {
  // 清除标记点
  markers.forEach(marker => {
    if (map) {
      map.removeOverlay(marker);
    }
  });
  markers.length = 0;
  
  // 清除信息窗口
  infoWindows.length = 0;
  
  // 清除飞线
  flylineOverlays.forEach(overlay => {
    if (map) {
      map.removeOverlay(overlay);
    }
  });
  flylineOverlays.length = 0;
  
  // 清除地图上所有覆盖物
  if (map) {
    map.clearOverlays();
  }
}

// 添加飞线效果
function addBMapFlylines() {
  if (!map || !BMapGL) return;
  
  mockFlylineData.forEach(line => {
    const fromPoint = new BMapGL.Point(line.coords[0][0], line.coords[0][1]);
    const toPoint = new BMapGL.Point(line.coords[1][0], line.coords[1][1]);
    
    // 创建弧线
    const points = [fromPoint, toPoint];
    const curve = new BMapGL.Polyline(points, {
      strokeColor: '#FF8C00',
      strokeWeight: 2,
      strokeOpacity: 0.6
    });
    
    map.addOverlay(curve);
    flylineOverlays.push(curve);
    
    // 添加动画效果（使用自定义覆盖物和CSS动画）
    const flyingDot = createFlyingDot(fromPoint, toPoint);
    map.addOverlay(flyingDot);
    flylineOverlays.push(flyingDot);
  });
}

// 创建飞行点效果
function createFlyingDot(fromPoint, toPoint) {
  // 自定义覆盖物
  function FlyingDot() {}
  
  // 继承百度地图覆盖物类
  FlyingDot.prototype = new BMapGL.Overlay();
  
  // 初始化覆盖物
  FlyingDot.prototype.initialize = function(map) {
    this._map = map;
    this._div = document.createElement("div");
    this._div.style.position = "absolute";
    this._div.style.width = "6px";
    this._div.style.height = "6px";
    this._div.style.backgroundColor = "#ffffff";
    this._div.style.borderRadius = "50%";
    this._div.style.boxShadow = "0 0 5px #ffffff";
    this._div.style.zIndex = BMapGL.Overlay.getZIndex(toPoint.lat);
    this._div.style.animation = "flying 3s linear infinite";
    
    // 添加CSS动画
    const style = document.createElement("style");
    style.type = "text/css";
    style.innerHTML = `
      @keyframes flying {
        0% {
          transform: translate(0, 0) scale(0.5);
          opacity: 0;
        }
        50% {
          transform: translate(${(toPoint.lng - fromPoint.lng) * 50}%, ${(toPoint.lat - fromPoint.lat) * 50}%) scale(1);
          opacity: 1;
        }
        100% {
          transform: translate(${(toPoint.lng - fromPoint.lng) * 100}%, ${(toPoint.lat - fromPoint.lat) * 100}%) scale(0.5);
          opacity: 0;
        }
      }
    `;
    document.getElementsByTagName("head")[0].appendChild(style);
    
    map.getPanes().labelPane.appendChild(this._div);
    return this._div;
  };
  
  // 绘制覆盖物
  FlyingDot.prototype.draw = function() {
    const position = this._map.pointToOverlayPixel(fromPoint);
    this._div.style.left = position.x + "px";
    this._div.style.top = position.y + "px";
  };
  
  return new FlyingDot();
}

// 使用ECharts初始化地图
function initEChartsMap() {
  if (chart) {
    chart.dispose();
  }
  
  // 初始化ECharts实例
  chart = echarts.init(document.getElementById('mapContainer'));
  
  // 设置地图配置项
  const option = {
    backgroundColor: '#0a1633',
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.2,
      center: [104.114129, 33.550339],
      itemStyle: {
        normal: {
          areaColor: '#132937',
          borderColor: '#0692a4'
        },
        emphasis: {
          areaColor: '#0b1c2d'
        }
      }
    },
    series: [
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        data: mockLocationData.map(item => ({
          name: item.name,
          value: [...item.value, item.count],
          itemStyle: {
            color: item.type === 'online' ? '#67C23A' : 
                  item.type === 'offline' ? '#909399' : 
                  '#F56C6C'
          }
        })),
        symbolSize: 10,
        label: {
          normal: {
            show: false
          },
          emphasis: {
            show: true,
            formatter: '{b}'
          }
        },
        emphasis: {
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          }
        }
      }
    ]
  };
  
  // 应用配置项
  chart.setOption(option);
  
  // 更新统计数据
  updateStatistics();
}

// 更新飞线效果
function toggleFlylines() {
  showFlylines.value = !showFlylines.value;
  
  if (map && BMapGL) {
    // 百度地图飞线效果
    if (showFlylines.value) {
      addBMapFlylines();
    } else {
      // 清除飞线
      flylineOverlays.forEach(overlay => {
        map.removeOverlay(overlay);
      });
      flylineOverlays.length = 0;
    }
  } else if (chart) {
    // 使用ECharts实现飞线效果
    updateEChartsMap();
  }
}

// 切换3D柱状图
function toggle3DBar() {
  show3DBar.value = !show3DBar.value;
  
  if (map && BMapGL) {
    // 百度地图暂不直接支持3D柱状图，切换到ECharts模式
    if (show3DBar.value) {
      if (map) {
        map.destroy && map.destroy();
        map = null;
      }
      updateEChartsMap();
    } else {
      if (chart) {
        chart.dispose();
        chart = null;
      }
      initBMap();
    }
  } else if (chart) {
    // 使用ECharts更新地图
    updateEChartsMap();
  }
}

// 更新ECharts地图
function updateEChartsMap() {
  if (!chart) {
    initEChartsMap();
    return;
  }
  
  const series = [
    {
      type: 'scatter',
      coordinateSystem: 'geo',
      data: mockLocationData.map(item => ({
        name: item.name,
        value: [...item.value, item.count],
        itemStyle: {
          color: item.type === 'online' ? '#67C23A' : 
                item.type === 'offline' ? '#909399' : 
                '#F56C6C'
        }
      })),
      symbolSize: 10,
      label: {
        normal: {
          show: false
        },
        emphasis: {
          show: true,
          formatter: '{b}'
        }
      },
      emphasis: {
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        }
      }
    }
  ];
  
  // 添加飞线效果
  if (showFlylines.value) {
    series.push({
      type: 'lines',
      coordinateSystem: 'geo',
      data: mockFlylineData.map(item => ({
        fromName: item.fromName,
        toName: item.toName,
        coords: item.coords,
        value: item.count
      })),
      lineStyle: {
        normal: {
          color: '#FF8C00',
          width: 2,
          opacity: 0.6,
          curveness: 0.2
        }
      },
      effect: {
        show: true,
        period: 6,
        trailLength: 0.7,
        color: '#fff',
        symbolSize: 3
      }
    });
  }
  
  // 添加3D柱状图效果
  if (show3DBar.value) {
    series.push({
      type: 'bar3D',
      coordinateSystem: 'geo3D',
      data: mockLocationData.map(item => ({
        name: item.name,
        value: [...item.value, item.count],
        itemStyle: {
          color: item.count > 100 ? '#ff5722' : 
                 item.count > 70 ? '#ffeb3b' : 
                 '#00bcd4'
        }
      })),
      barSize: 0.6,
      minHeight: 0.2,
      silent: false,
      shading: 'lambert',
      opacity: 0.8
    });
  }
  
  // 更新ECharts配置
  chart.setOption({
    series: series
  });
}

// 获取地图样式
function getMapStyle() {
  const styles = {
    midnight: 'midnight',  // 深蓝
    normal: 'normal',      // 标准
    earth: 'earth'         // 卫星
  };
  
  return styles[mapTheme.value] || 'midnight';
}

// 设置地图主题
function setMapTheme(theme) {
  if (map && BMapGL) {
    const styleJson = getMapStyleJson(theme);
    map.setMapStyleV2({ styleJson });
  }
}

// 获取地图样式JSON
function getMapStyleJson(theme) {
  let styleJson = [];
  
  switch(theme) {
    case 'midnight':
      // 深蓝风格
      styleJson = [
        {
          "featureType": "water",
          "elementType": "all",
          "stylers": { "color": "#044161" }
        },
        {
          "featureType": "land",
          "elementType": "all",
          "stylers": { "color": "#091934" }
        },
        {
          "featureType": "boundary",
          "elementType": "all",
          "stylers": { "color": "#064f85" }
        },
        {
          "featureType": "railway",
          "elementType": "all",
          "stylers": { "visibility": "off" }
        },
        {
          "featureType": "highway",
          "elementType": "all",
          "stylers": { "color": "#004981" }
        },
        {
          "featureType": "all",
          "elementType": "labels",
          "stylers": { "lightness": -10, "color": "#ffffff" }
        }
      ];
      break;
    case 'earth':
      // 卫星风格，使用百度地图自带卫星图
      map.setMapType(BMAP_SATELLITE_MAP);
      return [];
    case 'normal':
    default:
      // 正常风格
      map.setMapType(BMAP_NORMAL_MAP);
      return [];
  }
  
  return styleJson;
}

// 更新统计数据
function updateStatistics() {
  statistics.projects = mockLocationData.length;
  statistics.online = mockLocationData.filter(item => item.type === 'online').length;
  statistics.offline = mockLocationData.filter(item => item.type === 'offline').length;
  statistics.alarms = mockLocationData.filter(item => item.type === 'alarm').length;
}

// 更换地图主题
function changeMapTheme() {
  if (map && BMapGL) {
    setMapTheme(mapTheme.value);
  } else if (chart) {
    // 如果是ECharts地图，需要重新渲染
    updateEChartsMap();
  }
}

// 刷新地图
function refreshMap() {
  if (map && BMapGL) {
    clearOverlays();
    map = null;
  }
  
  if (chart) {
    chart.dispose();
    chart = null;
  }
  
  initBMap();
}

// 生命周期钩子
onMounted(() => {
  initBMap();
  
  // 添加窗口大小改变事件监听
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁实例
  clearOverlays();
  
  if (map && map.destroy) {
    map.destroy();
  }
  
  if (chart) {
    chart.dispose();
  }
});

// 处理窗口大小改变
function handleResize() {
  if (chart) {
    chart.resize();
  }
}
</script>

<style scoped lang="scss">
.dashboard {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background-color: #0a1633;
  color: #fff;
  
  .statistics-row {
    margin-bottom: 15px;
    
    .statistics-card {
      height: 100px;
      background-color: rgba(28, 42, 80, 0.7);
      border: none;
      
      :deep(.el-card__body) {
        padding: 10px;
      }
      
      .statistics-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        
        .number-container {
          display: flex;
          align-items: center;
          justify-content: center;
          
          .number {
            font-size: 32px;
            font-weight: bold;
            color: #00ffff;
          }
        }
        
        .label {
          font-size: 14px;
          color: #aaa;
          margin-top: 5px;
        }
        
        .control-panel {
          display: flex;
          gap: 10px;
        }
      }
    }
  }
  
  .map-container {
    flex: 1;
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    #mapContainer {
      width: 100%;
      height: 100%;
    }
    
    .map-controls {
      position: absolute;
      bottom: 20px;
      left: 20px;
      display: flex;
      flex-direction: column;
      gap: 5px;
      z-index: 100;
      
      .map-button {
        background-color: rgba(0, 0, 0, 0.6);
        color: white;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        
        &:hover {
          background-color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
}
</style>

